/*
@auther fenglei
*/
package xxdb

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

type MongoOptions struct {
	DSN         string
	MaxPoolSize int
}

// NewMySQL create a new gorm db instance with the given options.
func NewMongo(opts *MongoOptions) (*mongo.Client, error) {
	if opts.DSN == "" {
		return nil, fmt.Errorf("DNS is nil")
	}
	// Set default values to ensure all fields in opts are available.
	setMongoDefaults(opts)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(opts.DSN).SetMaxPoolSize(10)) // 连接池
	if err != nil {
		return nil, err
	}
	return client, nil
}

// setMySQLDefaults set available default values for some fields.
func setMongoDefaults(opts *MongoOptions) {
	if opts.MaxPoolSize == 0 {
		opts.MaxPoolSize = 10
	}
}
func CloseMongo(mongo *mongo.Client) error {
	return mongo.Disconnect(context.Background())
}
